<template>
  <div class="parent-container">
    <div class="map-container">
      <div id="mapBox" class="map-box"></div>
    </div>
    <button class="checkin-btn" @click="handleCheckIn">立即签到</button>
  </div>
</template>

<script>
import { isLocationOutOfChina, transformFromWGSToGCJ, transformFromGCJToBaidu } from '@/plugins/geolocation/geolocation.js';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import store from '@/store';
import axios from "axios";
import router from "@/router";

export default {
  data() {
    return {
      map: null,
      userMarker: null,
      centerMarker: null,
      circle: null,
      userLocation: null,
      targetLocation: {
        latitude: 31.2833,
        longitude: 118.3676,
        radius: 500
      },
      checkInRecord: null, // 用于存储从接口获取的签到记录数据
      api: axios.create({
        baseURL: store.getters.getBaseURL
      }),
      aid: null, // 从路由中获取的签到活动 ID
      rid: null,
      isVerify: null
    };
  },
  mounted() {
    const route = useRoute()
    const isVerify = route.query.isVerify;
    if (isVerify === '1' && sessionStorage.getItem(`${route.params.id}`) !== '1') {
      router.push({ path: `/verification/${isVerify}`, query: { section: route.params.id }});
    }
    this.initMap();
    this.getUserLocation();
    this.getRouteParams();
    this.fetchCheckInRecord(); // 获取签到记录数据
  },
  methods: {
    initMap() {
      this.map = new BMapGL.Map("mapBox");
      const defaultPoint = new BMapGL.Point(116.3975, 39.9087);
      this.map.centerAndZoom(defaultPoint, 15);
      this.map.enableScrollWheelZoom(true);
    },

    async getUserLocation() {
      try {
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000
          });
        });

        this.processCoordinates({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude
        });
      } catch (error) {
        console.error("定位失败:", error);
        this.useDefaultLocation();
      }
    },

    processCoordinates(coords) {
      let finalCoords = { ...coords };

      if (!isLocationOutOfChina(coords.latitude, coords.longitude)) {
        const gcj02 = transformFromWGSToGCJ(coords.latitude, coords.longitude);
        finalCoords = transformFromGCJToBaidu(gcj02.latitude, gcj02.longitude);
      }

      this.userLocation = finalCoords;
      this.updateUserMarker();
      this.drawCheckArea();
    },

    updateUserMarker() {
      if (this.userMarker) this.map.removeOverlay(this.userMarker);

      const point = new BMapGL.Point(this.userLocation.longitude, this.userLocation.latitude);

      this.userMarker = new BMapGL.Marker(point, { draggable: false });
      this.map.addOverlay(this.userMarker);
      this.map.centerAndZoom(point, 17);

      const infoWindow = new BMapGL.InfoWindow(
          `您的位置<br/>经度：${this.userLocation.longitude.toFixed(6)}<br/>纬度：${this.userLocation.latitude.toFixed(6)}`,
          {
            offset: new BMapGL.Size(0, -30),
            enableHTML: true
          }
      );
      this.userMarker.addEventListener("click", () => {
        this.userMarker.openInfoWindow(infoWindow);
      });
    },

    drawCheckArea() {
      let targetCoords = {
        longitude: this.targetLocation.longitude,
        latitude: this.targetLocation.latitude
      };

      if (this.centerMarker) this.map.removeOverlay(this.centerMarker);
      const centerPoint = new BMapGL.Point(targetCoords.longitude, targetCoords.latitude);

      const centerIcon = new BMapGL.Icon(
          "//api.map.baidu.com/images/marker.png",
          new BMapGL.Size(20, 20),
          { anchor: new BMapGL.Size(10, 20) }
      );

      this.centerMarker = new BMapGL.Marker(centerPoint, { icon: centerIcon });
      this.map.addOverlay(this.centerMarker);

      if (this.circle) this.map.removeOverlay(this.circle);
      this.circle = new BMapGL.Circle(centerPoint, this.targetLocation.radius, {
        strokeColor: "#FF0000",
        fillColor: "#FF0000",
        strokeOpacity: 0.3,
        fillOpacity: 0.1,
        strokeWeight: 2
      });
      this.map.addOverlay(this.circle);
    },

    convertToBaidu(coords) {
      if (isLocationOutOfChina(coords.latitude, coords.longitude)) return coords;
      const gcj02 = transformFromWGSToGCJ(coords.latitude, coords.longitude);
      return transformFromGCJToBaidu(gcj02.latitude, gcj02.longitude);
    },

    handleCheckIn() {
      if (!this.userLocation) {
        ElMessage.error("请等待定位完成");
        return;
      }

      const userPoint = new BMapGL.Point(this.userLocation.longitude, this.userLocation.latitude);
      const targetCoords = {
        longitude: this.targetLocation.longitude,
        latitude: this.targetLocation.latitude
      };
      const targetPoint = new BMapGL.Point(targetCoords.longitude, targetCoords.latitude);

      const distance = this.map.getDistance(userPoint, targetPoint);

      if (distance <= this.targetLocation.radius) {
        this.checkInSubmit();
      } else {
        ElMessage.error(`签到失败！距离目标点还有${distance.toFixed(1)}米`);
      }
    },


    checkInSubmit() {
      if (!this.userLocation) {
        ElMessage.error('尚未获取用户位置信息');
        return;
      }
      const jobCode = sessionStorage.getItem('jobCode');

      this.api.put('/record/submit', {
        aid: this.aid, // 从路由中获取的签到活动 ID
        additionInfo: {
          locationDto: {
            latitude: this.userLocation.latitude,
            longitude: this.userLocation.longitude
          }
        }
      })
          .then(response => {
            if (response.data.code === 200) {
              ElMessage.success('签到成功');
              setTimeout(() => {
                router.push(`/${jobCode}/personalPage`);
              }, 1000);
            } else {
              ElMessage.error('签到失败');
            }
          })
          .catch(error => {
            console.error('提交失败:', error);
            ElMessage.error('请求失败');
          });
    },

    useDefaultLocation() {
      this.processCoordinates({ latitude: 39.9087, longitude: 116.3975 });
    },

    getRouteParams() {
      const route = useRoute();
      this.aid = parseInt(route.params.id); // 从路由中获取 aid 参数
      this.rid = route.query.rid;
      this.isVerify = route.query.isVerify; // 从路由中获取 isVerify 参数
    },

    fetchCheckInRecord() {
      if (!this.rid) {
        console.error("未获取到签到活动 ID");
        return;
      }
      this.api.get(`/record/rid/${this.rid}`)
          .then(response => {
            if (response.data.code === 200) {
              this.checkInRecord = response.data.data;
              const locationInfo = this.checkInRecord.additionInfoDto.locationDto;
              this.targetLocation = {
                latitude: locationInfo.latitude,
                longitude: locationInfo.longitude,
                radius: locationInfo.range
              };
              this.drawCheckArea(); // 重新绘制检查区域
            } else {
              ElMessage.error('获取签到记录失败');
            }
          })
          .catch(error => {
            console.error('获取签到记录失败:', error);
            ElMessage.error('获取签到记录失败');
          });
    }
  },
  created() {
    // 添加请求拦截器
    this.api.interceptors.request.use(config => {
      const token = sessionStorage.getItem('userToken');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

    // 添加响应拦截器
    this.api.interceptors.response.use(
        response => response,
        error => {
          if (error.response?.status === 401) {
            router.push('/loginAndRegister');
          }
          return Promise.reject(error);
        }
    );
  }
};
</script>

<style scoped>
.parent-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
}

.map-container {
  position: relative;
  width: 300px;
  height: 300px;
  margin: 20px auto;
  border: 2px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.map-box {
  width: 100%;
  height: 100%;
  background: #f0f2f5;
}

.checkin-btn {
  margin-top: 20px;
  padding: 12px 24px;
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 25px;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  transition: all 0.3s;
}

.checkin-btn:hover {
  background: #66b1ff;
  transform: scale(1.05);
}
</style>